from flask import Flask, render_template, request, jsonify, redirect, url_for, session
import requests
import os
import argparse

# 解析命令行参数
parser = argparse.ArgumentParser(description='Flask frontend for Neo4j Manager')
parser.add_argument('--port', type=int, default=5000, help='Port to run the server on')
args = parser.parse_args()

# 初始化Flask应用
app = Flask(__name__)
app.secret_key = os.urandom(24)  # 用于会话管理

# 后端API地址
BACKEND_API_URL = "http://localhost:8001"

# 首页路由
@app.route("/")
def index():
    if "username" not in session:
        return redirect(url_for("login"))
    return render_template("index.html")

# 登录路由
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        
        # 调用后端登录API
        try:
            response = requests.post(
                f"{BACKEND_API_URL}/auth/token",
                data={"username": username, "password": password},
                headers={"Content-Type": "application/x-www-form-urlencoded"}
            )
            
            if response.status_code == 200:
                token_data = response.json()
                session["username"] = username
                session["token"] = token_data["access_token"]
                return redirect(url_for("index"))
            else:
                return render_template("login.html", error="用户名或密码错误")
        except Exception as e:
            return render_template("login.html", error=f"登录失败: {str(e)}")
    
    return render_template("login.html")

# 注册路由
@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        email = request.form["email"]
        password = request.form["password"]
        
        # 调用后端注册API
        try:
            response = requests.post(
                f"{BACKEND_API_URL}/auth/register",
                params={"username": username, "email": email, "password": password}
            )
            
            if response.status_code == 200:
                return redirect(url_for("login", success="注册成功，请登录"))
            else:
                error_data = response.json()
                return render_template("register.html", error=error_data.get("detail", "注册失败"))
        except Exception as e:
            return render_template("register.html", error=f"注册失败: {str(e)}")
    
    return render_template("register.html")

# 登出路由
@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))

# 搜索节点路由
@app.route("/search", methods=["GET"])
def search_nodes():
    if "username" not in session:
        return redirect(url_for("login"))
    
    search_string = request.args.get("q", "")
    if not search_string:
        return jsonify({"error": "搜索字符串不能为空"}), 400
    
    try:
        response = requests.get(f"{BACKEND_API_URL}/nodes/search/?search_string={search_string}")
        return response.json()
    except Exception as e:
        return jsonify({"error": f"搜索失败: {str(e)}"}), 500

# 获取节点详情路由
@app.route("/node/<node_id>", methods=["GET"])
def get_node(node_id):
    if "username" not in session:
        return redirect(url_for("login"))
    
    try:
        response = requests.get(f"{BACKEND_API_URL}/nodes/{node_id}")
        return response.json()
    except Exception as e:
        return jsonify({"error": f"获取节点详情失败: {str(e)}"}), 500

# 更新节点路由
@app.route("/node/<node_id>", methods=["PUT"])
def update_node(node_id):
    if "username" not in session:
        return redirect(url_for("login"))
    
    try:
        data = request.json()
        response = requests.put(f"{BACKEND_API_URL}/nodes/{node_id}", json=data)
        return response.json()
    except Exception as e:
        return jsonify({"error": f"更新节点失败: {str(e)}"}), 500

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=args.port)